<?php

namespace app\api\controller;

use app\api\model\Admin;
use app\api\model\ChuanglanSmsApi;
use app\api\model\Classes;
use app\api\model\Decrypt;
use app\api\model\Friends;
use app\api\model\Parents;
use app\api\model\ParentStudents;
use app\api\model\StudentImages;
use app\api\model\Students;
use app\api\model\TeacherClasses;
use app\api\model\Teachers;
use app\api\model\Users as UserModel;
use app\common\controller\Api;
use app\common\library\Token;
use app\common\library\Ems;
use app\common\library\Sms;
use fast\Random;
use think\Cache;
use think\Validate;

/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['auth', 'send'];
    protected $noNeedRight = ['*'];

    /**
     * 授权
     */
    public function auth()
    {
        $code = $this->request->post('code');
        if (empty($code)) {
            $this->error('code不能为空');
        }
        //小程序登录
        $url = sprintf(config('wechat.auth_url'), config('wechat.app_id'), config('wechat.app_secret'), $code);
        $res = curl_get($url);
        if (isset($res['errcode']) && $res['errcode']) {
            $this->error($res['errmsg'], [], $res['errcode']);
        }
        //是否首次授权
        $user = UserModel::where('openid', $res['openid'])->find();

        if (!$user) {
            $user = UserModel::create([
                'openid' => $res['openid']
            ]);
        }
        //刷新token
        $token = md5(sha1(time().$res['openid'].$user->id));

        $result = Token::set($token, $user->id, 0);
        if (!$result) {
            $this->error('授权失败');
        }
        //缓存session_key
        Cache::set($token, $res['session_key'], 3600);
        $this->success('授权成功', ['token' => $token]);
    }

    /**
     * 更新头像昵称
     */
    public function update()
    {
        $data = $this->request->post();
        if (!$data) {
            $this->error('请求参数不能为空');
        }

        $user = UserModel::find($this->auth->getUserId());
        if (!$user) {
            $this->error('用户不存在');
        }

        $user->head = $data['head'] ?? $user->head;
        $user->nickname = $data['nickname'] ?? $user->nickname;
        $user->phone = $data['phone'] ?? $user->phone;
        $result = $user->save();
        $result ? $this->success('更新成功') : $this->error('更新失败');
    }

    /**
     * 用户信息
     */
    public function info()
    {
        $user = UserModel::find($this->auth->getUserId());
        if (!$user) {
            $this->error('用户不存在');
        }
        //身份
        $user->status = 0;
        $user->parent_id = 0;
        $parent = Parents::getByPhone($user->phone);
        if ($parent) {
            $user->status = 1;
            $user->parent_id = $parent->id;
        } else {
            $friend = Friends::getFriendByUser($user->phone);
            if ($friend) {
                $user->status = 2;
                $user->parent_id = $friend->parent_id;
            }
        }
        $student_ids = ParentStudents::getStudentIds($user->parent_id);
        $students = Students::getStudentsByIds($student_ids);
        $class_ids = array_column($students, 'class_id');
        $classes = Classes::getClassesbyId($class_ids);

        $user->classes = $classes;
        $user->students = $students;

        $this->success('请求成功', ['user' => $user]);
    }

    /**
     * 微信小程序解密数据
     */
    public function decryptData()
    {
        $encryptedData = $this->request->post('encryptedData');
        $iv = $this->request->post('iv');
        $token = $this->request->header('token');
        $session_key = Cache::get($token);
        if (strlen($session_key) != 24) {
            $this->error('session_key无效', [], -41001);
        }
        if (strlen($iv) != 24) {
            $this->error('iv无效', [], -41002);
        }
        $aesKey = base64_decode($session_key);
        $aesIV = base64_decode($iv);
        $aesCipher = base64_decode($encryptedData);
        $result = openssl_decrypt($aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);
        $data = json_decode($result, true);
        if (!$data) {
            $this->error('没有数据', [], -41003);
        }
        if( $data['watermark']['appid'] != config('wechat.app_id') ) {
            $this->error('appid无效', [], -41003);
        }
        $this->success('请求成功', $data);
    }

    /**
     * 我的相册
     */
    public function photos($student_id)
    {
        $date = $this->request->get('date');
        if ($date) {
            //教师端的学生相册
            $images = StudentImages::getImagesByDate($student_id, $date);
            $status = 'teacher';
        } else {
            $images = StudentImages::getImagesByStudent($student_id);
            $status = 'parent';
        }

        $images ? $this->success('请求成功', compact('images', 'status')) : $this->error('暂无相册');
    }


    /**
     * 发送短信
     */
    public function send(ChuanglanSmsApi $chuanglanSmsApi)
    {
        $phone = $this->request->post('phone');
        if (empty($phone)) {
            $this->error("手机号不能为空");
        }
        if (!preg_match("/^1[3-9][0-9]{9}$/", $phone)) {
            $this->error("手机号格式不正确");
        }
        $code = mt_rand(100000, 999999);
        $runtime = 5;
        $msg = '【优米】您的验证码是{$var}，此验证码只用于登录，{$var}分钟内有效,感谢您的使用。';
        $params = "{$phone},{$code},{$runtime}";
        $result = $chuanglanSmsApi->sendVariableSMS($msg, $params);
        //"{\"code\":\"0\",\"failNum\":\"0\",\"successNum\":\"1\",\"msgId\":\"20051114125200202001000003172836\",\"time\":\"20200511141252\",\"errorMsg\":\"\"}"
        $result = json_decode($result, true);
        //发送成功
        if (isset($result['code']) && $result['code'] == 0) {
            Cache::set("sms_".$code, $code, $runtime * 60);
            Cache::set("sms_".$phone, $phone, $runtime * 60);
            $this->success("请求成功", compact('code'));
        } else {
            $this->success("获取验证码失败，请联系管理员");
        }
    }

    /**
     * 绑定手机
     */
    public function bind()
    {
        $phone = $this->request->post('phone');
        $code = $this->request->post('code');
        if (empty($phone) || empty($code)) {
            $this->error("手机号和验证码都不能为空");
        }
        $cache_code = Cache::get("sms_".$code);
        $cache_phone = Cache::get("sms_".$phone);
        if ($cache_code != $code) {
            $this->error("验证码无效或已过期，请重新发送验证码");
        }
        if ($phone != $cache_phone) {
            $this->error("请输入接收验证码的手机号");
        }
        $user = UserModel::find($this->auth->getUserId());
        if (!$user) {
            $this->error('用户不存在');
        }
        $user->phone = $phone;
        $result = $user->save();
        $result ? $this->success("请求成功") : $this->error("请求失败");
    }
}
